<?php

namespace Wechat\Controller;
use Org\Util\Wechat;
class WechatuserController extends BaseController{
    /*微信用户页面*/
    public function index()
    {
        $count      = M('wechatuser')->count();// 查询满足要求的总记录数
        $Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(10)
        $Page->setConfig('theme',"%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%");
        $show       = $Page->show();// 分页显示输出

        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $list = M('wechatuser')->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();

        $this->assign(['page'=>$show,'data'=>$list]);
        $this->display();
    }
    /*配对微信*/
    public function check()
    {
        $op = M('wechat')->find(1);
        $options = [
            'token'=>$op['token'],
            'appid'=>$op['appid'],
            'appsecret'=>$op['appsecret'],
        ];

        $weObj = new Wechat($options);
        $weObj->valid();
        //获取菜单操作
        $menu  = $weObj->getMenu();
        //设置菜单
        $newmenu = [
            "button"=>[
                ['type'=>'view','name'=>'最新商品','url'=>'http://www.amijie.top/index.php?g=Wechat&m=Wechatuser&a=open'],
                ['type'=>'view','name'=>'分享榜','url'=>'http://www.amijie.top/index.php?g=Face&m=User&a=fenxiang'],
                ['type'=>'view','name'=>'个人中心','url'=>'http://www.amijie.top/index.php?g=Wechat&m=Wechatuser&a=openi'],
            ]
        ];
        $result = $weObj->createMenu($newmenu);

        $type = $weObj->getRev()->getRevType();
        switch($type) {
            case Wechat::MSGTYPE_TEXT:
                $weObj->text('有事请联系客服哦~')->reply();
                exit;
                break;
            case Wechat::MSGTYPE_EVENT:
                $weObj->text('欢迎你来到米透~')->reply();
                break;
            case Wechat::MSGTYPE_IMAGE:
                $weObj->text("看到了！")->reply();
                break;
            default:
                $weObj->text("help info")->reply();
        }

    }
    /*个人中心*/
    public function openi()
    {
        $num = i('get.num');
        $op = M('wechat')->find(1);

        $redirecturl= urlencode("http://www.amijie.top/index.php?g=Wechat&m=Wechatuser&a=openidi&num=$num");
        $appid=$op['appid'];
        $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirecturl.'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
        header("Location:$url");
    }
    /*获取微信用户信息*/
    public function openidi()
    {
        $num = i('get.num');
        $op = M('wechat')->find(1);
        $code= $_GET['code'];
        $appid= $op['appid'];
        $appsecret= $op['appsecret'];

        $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";



        $ch=curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $data=curl_exec($ch);
        curl_close($ch);
        $jsoninfo=json_decode($data,true);
        $access_token=$jsoninfo['access_token'];
        $openid = $jsoninfo['openid'];

        $_SESSION['access_token'] = $access_token;

        $urll = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";

        $ch=curl_init();
        curl_setopt($ch,CURLOPT_URL,$urll);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $data=curl_exec($ch);
        curl_close($ch);
        $jsoninfo=json_decode($data,true);
        $nickname=$jsoninfo['nickname'];
        $openid = $jsoninfo['openid'];
        $headimg = $jsoninfo['headimgurl'];

        $_SESSION['wechatopenid']=$openid;
        $_SESSION['wechatimg']=$headimg;
        $_SESSION['wechatname']=$nickname;

        $data = [
            'name'=>$nickname,
            'openid'=>$openid,
            'headimg'=>$headimg,
            'money'=>0,
            'jifen'=>100,
            'yaoqingma'=>rand(0,9).rand(1,9).rand(0,9).rand(0,9),rand(0,9),rand(0,9),
            'lastlogin'=>time(),
        ];
        $save = [
            'name'=>$nickname,
            'openid'=>$openid,
            'headimg'=>$headimg,
        ];
        if(M('wechatuser')->where(['openid'=>$openid])->find()){
            M('wechatuser')->where(['openid'=>$openid])->save($save);
            if($num!=NULL){
                $this->redirect('Face/User/hello',['num'=>$num],0,NULL);
            }
            $this->redirect('Face/User/index');
        }else{
            M('wechatuser')->add($data);
            if($num!=NULL){
                $this->redirect('Face/User/hello',['num'=>$num],0,NULL);
            }
            $this->redirect('Face/User/index');

        }
    }


    /*获取微信code*/
    public function open()
    {
        $op = M('wechat')->find(1);

        $redirecturl= urlencode("http://www.amijie.top/index.php?g=Wechat&m=Wechatuser&a=openid");
        $appid=$op['appid'];
        $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirecturl.'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
        header("Location:$url");
    }
    /*获取微信用户信息*/
    public function openid()
    {
        $op = M('wechat')->find(1);
        $code= $_GET['code'];
        $appid= $op['appid'];
        $appsecret= $op['appsecret'];

        $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";



        $ch=curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $data=curl_exec($ch);
        curl_close($ch);
        $jsoninfo=json_decode($data,true);
        $access_token=$jsoninfo['access_token'];

        $_SESSION['access_token'] = $access_token;
        //var_dump($access_token);
        //die();
        $openid = $jsoninfo['openid'];

        $urll = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";

        $ch=curl_init();
        curl_setopt($ch,CURLOPT_URL,$urll);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $data=curl_exec($ch);
        curl_close($ch);
        $jsoninfo=json_decode($data,true);
        $nickname=$jsoninfo['nickname'];
        $openid = $jsoninfo['openid'];
        $headimg = $jsoninfo['headimgurl'];

        $_SESSION['wechatopenid']=$openid;
        $_SESSION['wechatimg']=$headimg;
        $_SESSION['wechatname']=$nickname;

        $data = [
          'name'=>$nickname,
            'openid'=>$openid,
            'headimg'=>$headimg,
            'money'=>2.55,
            'jifen'=>100,
            'yaoqingma'=>rand(0,9).rand(1,9).rand(0,9).rand(0,9),rand(0,9),rand(0,9),
            'lastlogin'=>time(),
        ];
        $save = [
            'name'=>$nickname,
            'openid'=>$openid,
            'headimg'=>$headimg,
        ];
        if(M('wechatuser')->where(['openid'=>$openid])->find()){
            M('wechatuser')->where(['openid'=>$openid])->save($save);
            $this->redirect('Face/Index/index');
        }else{
            M('wechatuser')->add($data);
            $this->redirect('Face/Index/index');
        }
    }

    public function options()
    {
        $this->assign('data',M('wechat')->find(1));
        $this->display();
    }

    public function optionsedit()
    {
        //$mess = M('fankuijilu')->limit(1)->order('time desc')->find();
        //var_dump($mess['text']);
        //die();
        $id = i('get.id');
        $post = i('post.');
        $this->assign('old',M('wechat')->where(['id'=>$id])->find());
        if(IS_POST){
            if(trim(empty($post['appid'])) || trim(empty($post['appsecret'])) ){
                $this->error('请填写完整，');
            }
            if(trim(empty($post['token']))){
                $this->error('请填写token');
            }
            $data = [
              'appid'=>$post['appid'],
                'appsecret'=>$post['appsecret'],
                'token'=>$post['token'],
                'encodingaeskey'=>$post['encodingaeskey'],
            ];
            if(M('wechat')->where(['id'=>$id])->save($data)){
                $this->success('Congratulation!  Successfully!!!');
            }else{
                $this->error('未知错误');
            }

        }else {
            $this->display();
        }
    }

    /*用户提现*/
    public function tixian()
    {
        $count      = M('tixian')->count();// 查询满足要求的总记录数
        $Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(10)
        $Page->setConfig('theme',"%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%");
        $show       = $Page->show();// 分页显示输出

        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $list = M('tixian')->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();

        $this->assign(['page'=>$show,'data'=>$list]);
        $this->display();
    }
    /*删除提现记录*/
    public function tixiande()
    {
        $id= i('get.id');
        if(M('tixian')->where(['id'=>$id])->delete()){
            $this->success('成功，删除记录');
        }else{
            $this->success('未知错误');
        }
    }
    /*金额设定*/
    public function jine()
    {
        $this->assign('vo',M('fankui')->find(1));
        $post = i('post.');
        if(IS_POST){
            if(trim(empty($post['yaoqing']))){
                $this->error('邀请金额不能为空');
            }
            if(trim(empty($post['fenxiang']))){
                $this->error('分享金额不能为空');
            }
            if(trim(empty($post['yuedu']))){
                $this->error('阅读金额不能为空');
            }
            if(trim(empty($post['shangjia']))){
                $this->error('上家金额不能为空');
            }
            if(trim(empty($post['jifen']))){
                $this->error('反馈积分不能为空');
            }
            /*
            if(trim(empty($post['lingqian']))){
                $this->error('购买商品反馈零钱不能为空');
            }
            */
            $data = [
                'yaoqing'=>$post['yaoqing'],
                'fenxiang'=>$post['fenxiang'],
                'yuedu'=>$post['yuedu'],
                'shangjia'=>$post['shangjia'],
                'jifen'=>$post['jifen'],
                //'lingqian'=>$post['lingqian'],
            ];
            if(M('fankui')->where(['id'=>1])->save($data)){
                $this->success('修改金额成功');
            }else{
                $this->error('修改失败，未知错误。');
            }
        }else{
            $this->display();
        }
    }
    /*评论管理*/
    public function pinglun()
    {
        $count      = M('pinglun')->count();// 查询满足要求的总记录数
        $Page       = new \Think\Page($count,20);// 实例化分页类 传入总记录数和每页显示的记录数(10)
        $Page->setConfig('theme',"%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%");
        $show       = $Page->show();// 分页显示输出

        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $list = M('pinglun')->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();

        $this->assign(['page'=>$show,'data'=>$list]);
        $this->display();
    }
    /*评论删除*/
    public function pingluned()
    {
        $id = i('get.id');
        if(M('pinglun')->where(['id'=>$id])->delete()){
            $this->success('删除成功~');
        }else{
            $this->error('删除失败，未知错误');
        }
    }
}